<?php namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\LogoCropper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class SiteconfigController extends Controller {

	public function __construct() {
		$this->middleware('role:siteconfig');
	}

	/**
	 * 修改 Meta 信息
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function getMeta(Request $request) {
		$data['meta'] = config('site');
		$data['tongji'] = file_get_contents(public_path() . '/assets/tongji.js');
		return view('admin/siteconfig/meta', $data);
	}

	/**
	 * 编辑 Meta 信息
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function postSetMeta(Request $request) {
		$name = strval($request->input('name'));
		$title = strval($request->input('title'));
		$keywords = strval($request->input('keywords'));
		$description = strval($request->input('description'));
		$logo = config('site.logo');

		$tongji = $request->input('tongji');
		$js_file = realpath(public_path() . '/assets/tongji.js');
		if (file_exists($js_file)) {
			file_put_contents($js_file, $tongji);
		}

		$cfg_str = <<<EOF
<?php
return array(
  'name' => '$name',
  'title' => '$title',
  'keywords' => '$keywords',
  'description' => '$description',
  'logo' => '$logo',
);
EOF;

		$cfg_file = realpath(config_path() . DIRECTORY_SEPARATOR . 'site.php');
		if (!file_exists($cfg_file)) {
			return $this->error('配置文件丢失');
		}
		if (file_put_contents($cfg_file, $cfg_str)) {
			return $this->response('操作成功');
		}
		return $this->error('配置文件写入失败');
	}

	/**
	 * 进入 Logo 页面
	 * @return [type] [description]
	 */
	public function getLogo() {
		$logo = config('site.logo') ? config('site.logo') : 'upload/logo.png';
		return view('admin/siteconfig/logo')->withLogo(url($logo));
	}

	/**
	 * Logo 图片上传
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function postUploadLogo(Request $request) {
		$avatar_src = $request->input('avatar_src');
		$avatar_data = $request->input('avatar_data');
		$avatar_file = $_FILES['avatar_file'];

		$crop = new LogoCropper($avatar_src, $avatar_data, $avatar_file);
		$new_file = str_replace(upload_path(), 'upload', $crop->getResult());

		$cfg_file = realpath(config_path() . '/site.php');
		$cfg_str = file_get_contents($cfg_file);
		$pattern = '/([\s\S]*\'logo\' => \')(.*)(\'[\s\S]*)/s';
		$replacement = '$1' . $new_file . '$3';
		$new_str = preg_replace($pattern, $replacement, $cfg_str);
		file_put_contents($cfg_file, $new_str);

		$data = [
			'message' => $crop->getMsg(),
			'result' => url($new_file),
		];
		return $this->response($data);
	}

}
